package com.cjm.algorithm.leetcode.arr;

public class GenerateMatrix59 {
//    private static final int[][] xx = {{1,0},{0,1},{-1,0},{0,-1}};
    private static final int[][] xx = {{0,1},{1,0},{0,-1},{-1,0}};
    public int[][] generateMatrix(int n) {
        int nums = n * n;
        int startx = 0;
        int starty = 0;
        int cur = 1;
        int[][] res = new int[n][n];
        while (cur <= nums) {
            if (startx>=0&&startx<=(n-1) && starty>=0&&starty<=(n-1)) {
                res[startx][starty] = cur++;
                while ((startx + xx[0][0])>=0 && (startx + xx[0][0]) <= (n-1) &&
                        (starty + xx[0][1])>=0 && (starty + xx[0][1]) <= (n-1) &&
                        res[startx + xx[0][0]][starty + xx[0][1]] == 0) {
                    // 右
                    startx = startx + xx[0][0];
                    starty = starty + xx[0][1];
                    res[startx][starty] = cur++;
                }
                while ((startx + xx[1][0]) >= 0 && (startx + xx[1][0]) <= (n-1) &&
                        (starty + xx[1][1]) >= 0&&(starty + xx[1][1]) <= (n-1) &&
                        res[startx + xx[1][0]][starty + xx[1][1]] == 0) {
                    // 下
                    startx = startx + xx[1][0];
                    starty = starty + xx[1][1];
                    res[startx][starty] = cur++;
                }
                while ((startx + xx[2][0])>=0&&(startx + xx[2][0]) <= (n-1) &&
                        (starty + xx[2][1])>=0&&(starty + xx[2][1]) <= (n-1) &&
                        res[startx + xx[2][0]][starty + xx[2][1]] == 0) {
                    // 左
                    startx = startx + xx[2][0];
                    starty = starty + xx[2][1];
                    res[startx][starty] = cur++;
                }
                while ((startx + xx[3][0])>=0&&(startx + xx[3][0]) < (n-1) &&
                        (starty + xx[3][1])>=0&&(starty + xx[3][1]) < (n-1) &&
                        res[startx + xx[3][0]][starty + xx[3][1]] == 0) {
                    // 上
                    startx = startx + xx[3][0];
                    starty = starty + xx[3][1];
                    res[startx][starty] = cur++;
                }
                starty++;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        GenerateMatrix59 x = new GenerateMatrix59();
        int[][] ints = x.generateMatrix(2);
        System.err.println("OK");
    }
}
